<?php

namespace App\Http\Controllers\Admin;

use App\Enums\CriticalEnum;
use Carbon\Carbon;
use App\Traits\AdminLog;
use App\Response\Response;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use App\Services\Tools\CommonService;
use \App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

class PersonalController extends BaseController
{
    use AdminLog;

    public function __construct(Request $request)
    {
        $this->type = $request->input('type', 1);
        if (!in_array($this->type, range(1, 5))) {
            throw new BasicException(0, '奖池类型有误');
        }
        $this->pot_name = '奖池'.$this->type;
    }

    /**
     * @api {get} personal/pool 特殊个人奖池奖品列表
     * @apiVersion 0.1.0
     * @apiName 特殊个人奖池奖品列表
     * @apiGroup 幸运树
     * @apiParam {numeric} type 奖池类型1-5,必传
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total 礼物总金额": "521311346280319",
     * "left 礼物总个数": "1000009998",
     * "name": "奖池1",
     * "type": "1",
        "critical_gift_ids 可以暴击的礼物ids": [
        542,
        543
        ],
     * "list": [
     * {
     * "id": 4094,
     * "gift_id": 379,
     * "number": 48,
     * "gift_name": "周星*金冠",
     * "price": 999999999,
     * "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5fea93d5d9bde.png",
     * "special": "",
     *   "critical_times 暴击次数": 0,
     * "quality": "橙色"
     * }
     * ]
     * }
     * }
     */
    public function pool()
    {
        $field = ['a.id', 'a.gift_id', 'a.number', 'b.name as gift_name', 'b.price', 'b.picture', 'b.special','a.critical_times'];
        $list = DB::table('ln_personal_pool as a')
                  ->select($field)
                  ->leftJoin('ln_gift as b', 'a.gift_id', '=', 'b.id')
                  ->where('a.type', $this->type)
                  ->orderBy('b.price', 'desc')
                  ->get()->map(function ($item) {
                $item->quality = CommonService::giftRank($item->price);

                return $item;
            });
        $criticalGifts = app('model_critical_prize')->getModuleGiftIds(CriticalEnum::MODULE_TREE);
        $left = DB::table('ln_personal_pool as a')->where('type', $this->type)->sum('number');
        $total = DB::table('ln_personal_pool as a')
                   ->LeftJoin('ln_gift as b', 'b.id', '=', 'a.gift_id')
                   ->where('a.type', $this->type)
                   ->sum(DB::raw('a.number * b.price'));

        return Response::sendData([
            'total' => $total,
            'left'  => $left,
            'name'  => $this->pot_name,
            'type'  => $this->type,
            'critical_gift_ids'  => $criticalGifts,
            'list'  => $list,
        ]);
    }

    /**
     * @api {post} personal/pool 编辑特殊个人奖池
     * @apiVersion 0.1.0
     * @apiName 编辑特殊个人奖池
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型1-5,必传
     * @apiParam {numeric} id   如果传了id则为更新,否则添加,非必传
     * @apiParam {numeric} number   库存,必传
     * @apiParam {numeric} gift_id   礼物id,必传
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function updatePool(Request $request)
    {
        $data = $request->only(['gift_id', 'number']);
        $id = intval($request->input('id', 0));
        if (!isset($data['gift_id']) || $data['gift_id'] <= 0) {
            throw new BasicException(0, '请选择礼物');
        }
        if (!isset($data['number']) || $data['number'] < 0) {
            throw new BasicException(0, '数量不能小于0');
        }
        if ($id > 0) {
            DB::table('ln_personal_pool')->where('id', $id)->update($data);
        } else {
            $data['type'] = $this->type;
            DB::table('ln_personal_pool')->insert($data);
        }

        return Response::sendData('success');
    }

    /**
     * @api {post} personal/all 一键修改特殊个人奖池
     * @apiVersion 0.1.0
     * @apiName 一键修改特殊个人奖池
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,非必传 1,2,3,4,5分别对应本期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;11,12,13,14,15分别对应下期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;30特殊奖池
     * @apiParam {numeric} is_next   是否下期奖池1是0否,默认0,非必传
     * @apiParam {numeric} gift_detail   礼物数据json  [{"gift_id":377,"gift_name":"拐杖糖","number":2301}]
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function editAll(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'gift_detail' => 'required|string'
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));
        $data = $request->only(['gift_detail']);
        $giftDetailStr = $data['gift_detail'];
        $giftDetailList = json_decode($giftDetailStr, 1);
        foreach ($giftDetailList as $key => $value) {
            if (!isset($value['gift_id']) || $value['gift_id'] <= 0) {
                throw new BasicException(0, '请选择礼物');
            }
            if ($value['number'] < 0) {
                throw new BasicException(0, '数量不能小于0');
            }
            $whereArr = [];
            $whereArr[] = ["gift_id", "=", $value['gift_id']];
            $whereArr[] = ["type", "=", $this->type];
            DB::table('ln_personal_pool')->where($whereArr)->update(['number' => $value['number']]);
        }

        return Response::sendData('success');
    }

    /**
     * @api {delete} personal/pool 删除特殊个人奖池礼物
     * @apiVersion 0.1.0
     * @apiName 删除特殊个人奖池礼物
     * @apiGroup 幸运树
     * @apiParam {numeric} id   主键id,必传
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function deletePool(Request $request)
    {
        $id = $request->input('id', 0);
        $detail = DB::table('ln_personal_pool')->where('id', $id)->first();
        if (!$detail) {
            throw new BasicException(0, '数据有误');
        }
        DB::table('ln_personal_pool')->where('id', $id)->delete();

        return Response::sendData('success');
    }

    /**
     * @api {get} personal/user 特殊用户列表
     * @apiVersion 0.1.0
     * @apiName 特殊用户列表
     * @apiGroup 幸运树
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id": 4227,
     * "user_id": 643009,
     * "add_time": 1608360015,
     * "expired_time": 1608393600,
     * "status 1有效0无效": 1,
     * "add_type 1自动2手动": 2,
     * "total_income 特殊奖池累计产出": 215980,
     * "total_cost 特殊奖池累计投入": 40000,
     * "user_code": 560849,
     * "nickname": "气泡用户560849",
     * "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/default_avatar.png"
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 15,
     * "next": null,
     * "total": 4
     * },
     * "header": {
     * "number 每期排行数量": "1",
     * "types 奖池配置": [
     * "1",
     * "5"
     * ]
     * }
     * }
     * }
     */
    public function user()
    {
        $field = [
            'a.id',
            'a.user_id',
            'a.add_time',
            'a.expired_time',
            'a.status',
            'a.add_type',
            'a.total_income',
            'a.total_cost',
            'b.user_code',
            'b.nickname',
            'b.head_picture',
        ];
        $list = DB::table('ln_personal_pool_user as a')
                  ->select($field)
                  ->leftJoin('ln_user_data as b', 'a.user_id', '=', 'b.user_id')
                  ->orderBy('a.id', 'desc')
                  ->paginate();
        $config = app('model_config')->getValue('PERSONAL_POOL_CONFIG');

        return Response::sendList($list, [], [
            'number' => $config['number'] ?? 0,
            'types'  => isset($config['types']) && $config['types'] ? explode('-', $config['types']) : [],
        ]);
    }

    /**
     * @api {post} personal/user 编辑特殊用户
     * @apiVersion 0.1.0
     * @apiName 编辑特殊用户
     * @apiGroup 幸运树
     * @apiParam {numeric} id   如果传了id则为更新,否则添加,非必传
     * @apiParam {numeric} user_code   用户编号,必传
     * @apiParam {numeric} expired_time   过期时间,必传
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function updateUser(Request $request)
    {
        $user_code = $request->input('user_code');
        $expired_time = $request->input('expired_time');
        if ($expired_time <= Carbon::now()->timestamp) {
            throw new BasicException(0, '过期时间必须大于当前时间');
        }
        $id = intval($request->input('id', 0));
        if ($id > 0) {
            DB::table('ln_personal_pool_user')->where('id', $id)->update(['expired_time' => $expired_time]);
        } else {
            $user_id = app('model_user_data')->where('user_code', $user_code)->value('user_id');
            if (!$user_id) {
                throw new BasicException(0, '用户不存在');
            }
            if (DB::table('ln_personal_pool_user')->where('user_id', $user_id)->count() > 0) {
                throw new BasicException(0, '用户已有个人奖池');
            }
            DB::beginTransaction();
            $this->copyPersonalPool($user_id);
            $data = [
                'user_id'      => $user_id,
                'add_type'     => 2,
                'add_time'     => Carbon::now()->timestamp,
                'expired_time' => $expired_time,
            ];
            DB::table('ln_personal_pool_user')->insert($data);
            DB::commit();
        }

        return Response::sendData('success');
    }

    /**
     * @api {delete} personal/user 删除特殊用户
     * @apiVersion 0.1.0
     * @apiName 删除特殊用户
     * @apiGroup 幸运树
     * @apiParam {numeric} id   id,必传
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function deleteUser(Request $request)
    {
        $id = $request->input('id', 0);
        $detail = DB::table('ln_personal_pool_user')->where('id', $id)->first();
        if (!$detail) {
            throw new BasicException(0, '数据有误');
        }
        DB::table('ln_personal_pool_user')->where('id', $id)->delete();
        DB::table('ln_personal_pool_user_detail')->where('user_id', $detail->user_id)->delete();

        return Response::sendData('success');
    }

    public function copyPersonalPool($user_id)
    {
        //判断用户是否已存在个人奖池
        $result = DB::table('ln_personal_pool_user_detail')->where('user_id', $user_id)->count();
        if ($result > 0) {
            return false;
        }

        $config = app('model_config')->getValue('PERSONAL_POOL_CONFIG');
        if (empty($config)) {
            return false;
        } else {
            $types = explode('-', $config['types']);
            $pool_type = $types[array_rand($types)];
        }

        $data = DB::table('ln_personal_pool')->where('type', $pool_type)->select(['gift_id', 'number','critical_times'])->get();
        if ($data->isEmpty()) {
            return false;
        }
        $insertData = [];
        foreach ($data as $key => $value) {
            $insertData[] = [
                'user_id' => $user_id,
                'gift_id' => $value->gift_id,
                'number'  => $value->number,
                'critical_times'  => $value->critical_times,
                'type'    => $pool_type,
            ];
        }
        if (!empty($insertData)) {
            DB::table('ln_personal_pool_user_detail')->insert($insertData);
        }
    }

    /**
     * @api {post} personal/set 特殊个人奖池设置
     * @apiVersion 0.1.0
     * @apiName 特殊个人奖池设置
     * @apiGroup 幸运树
     * @apiParam {numeric} number   每期排行数量,必传
     * @apiParam {string} types   奖池类型用逗号隔开,如1,2,3,必传
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function set(Request $request)
    {
        $number = $request->input('number');
        $types = $request->input('types');
        if ($number < 0) {
            throw new BasicException(0, '数量有误');
        }
        $config = app('model_config')->getValue('PERSONAL_POOL_CONFIG');
        if (empty($config)) {
            throw new BasicException(0, '请先配置');
        }

        $config = 'number:'.$number.";types:".str_replace(',', '-', $types);
        app('model_config')->where('key', 'PERSONAL_POOL_CONFIG')->update(['value' => $config]);
        app('redis')->del('DB_CONFIG_DATA');

        return Response::sendData(1);
    }
}
